const mongoose = require("mongoose");
var User = mongoose.model("user");
var md5 = require('md5');


exports.findUser = function (req, res) {
    if (req.query.password) {
        req.query.password = md5(req.query.password);
    }
    // var _id = req.session.uid;
    // if(_id){
    //     req.query._id = _id;
    // }
    User.findOne(req.query, function (err, user) {
        if (!err) {
            if (req.query.password && user!=null) {
                req.session.uid = user._id;
                req.session.account = user.account;
            }
            res.json(user);
        }
        else {
            res.json({error: "findUser"});
        }
    })
}

exports.addUser = function (req, res) {
    var u = new User(req.body);
    u.password = md5(req.body.password);
    u.address={priority:1,address:req.body.address};
    u.save(function (err) {
        if (!err) {
            res.json(u);
        }
        else {
            res.json({error: "addUser"});
        }
    })
}

exports.findUserById = function (req, res) {
    User.findOne({_id:req.params._id},'-password',function (err,user) {
        if(!err){
            res.json(user);
        }else{
            res.json({error: 'error find user in find user by id'});
        }
    })
}

exports.updateInfo = function (req,res) {
    User.findOne({_id:req.params._id},function (err,user) {
        if(!err){
            if(req.body.password!=undefined){
                req.body.password = md5(req.body.password);
            }
            user.update(req.body,function (err,row) {
                if(!err){
                   User.findOne({_id:req.params._id},'-password',function(err,user){
                       if(!err){
                           res.json(user);
                       }else{
                           res.json({error: 'error find user in find user by id'});
                       }
                   });
                };
            })
        }else{
            res.json({error: 'error find user in update Info'});
        }
    })
}

exports.getSession =function (req,res) {
    if(req.session.uid!=undefined){
        var session = {
            uid: req.session.uid,
            account: req.session.account,
        }
        res.json(session);
    }else{
        res.json({});
    }
}
exports.clearSession = function (req,res) {
    req.session.uid= undefined;
    req.session.account= undefined;
    res.json({});
}